<?php
namespace OpenApi\Controller;
use Think\Controller;
//外部接口
class OrderController extends Controller {
    public function _initialize(){
		//数据库连接基础配置-begin
		C('db_config.DB_TYPE',C('DB_TYPE'));
		C('db_config.DB_HOST',C('DB_HOST'));
		C('db_config.DB_USER',C('DB_USER'));
		C('db_config.DB_PWD',C('DB_PWD'));
		C('db_config.DB_PORT',C('DB_PORT'));
		C('db_config.DB_CHARSET',C('DB_CHARSET'));
		//数据库连接基础配置-end
    }

	//接收订单
	public function order_bond(){
		$param	= file_get_contents("php://input");
		file_put_contents('./log/api/order_bond'.date('Y-m-d').'.log',date('Y-m-d H:i:s').var_export($param,true).PHP_EOL,FILE_APPEND);//日志导出sql
        $param=json_decode($param,true);

		$app_key = $param['appkey'];
        $timestamp = $param['timestamp'];
        $get_sign = $param['sign'];

        if(is_array($param['param'])){
            $param = $param['param'];
        }else{
            $param = json_decode($param['param'],true);
        }

        switch ($app_key) {
        	case 'test111':
        		$app_secret = '123456';
        		$info['user_code']='';
				$info['user_key']='';
				$info['merchant_code']='';
        		break;
        	case 'PNZgKvQpKfnWitLg':
        		$app_secret = 'Q5BYL4osudAXrbvrfGMmR76I3SKQXSg7';
        		$info['user_code']='PN1MBDNQ3G';
				$info['user_key']='PN1MBDNQ3G';
				$info['merchant_code']='PN1MBDNQ3G';
        		break;
        	case 'DFRhAhljCTi7LfGQ':
        		$app_secret = 'CSs7RLSiME9WWZqkG3x5uCa8gv34DVwh';
        		$info['user_code']='DF1X9GN675';
				$info['user_key']='DF1X9GN675';
				$info['merchant_code']='DF1X9GN675';
        		break;
        	default:
        		$app_secret = '';
        		break;
        }

        if(!$app_secret){
        	alert_json_new(0,'密钥参数错误');
        }

        if(!isset($param) || count($param)==0){
        	alert_json_new(0,'没有数据');
        }

        if($timestamp*1<time()*1-10){
        	alert_json_new(0,'请求过期,请重新发起');
        }

        $new_str = genVerify($param);
        $sign = md5($app_secret.'appkey'.$app_key.'param'.$new_str.'timestamp'.$timestamp.$app_secret);

        if($get_sign != $sign){
			alert_json_new(0,'验签失败');
        }

		//必传参数-订单表
        $must_param_order = ['order_no','buyer_name','buyer_phone','buyer_idcard','user_name','user_phone','user_province',
            'user_city','user_area','user_address','order_amount','order_tax','trade_model','apply_pay','apply_logistics',
            'apply_order','apply_list','platform_name','order_detail'];
        foreach ($must_param_order as $value){
            if(!isset($param[$value])){
                alert_json_new(0,'缺少订单参数：'.$value);
            }
        }

        //必传参数-产品表
        $must_param_goods = ['goods_sn','goods_price','goods_nums','goods_name'];
        foreach ($must_param_goods as $value){
            foreach ($param['order_detail'] as $k=>$good){
                if(!isset($good[$value])){
                    alert_json_new(0,'缺少产品参数：'.$value);
                }
                if(empty($good[$value])){
                	$msg['msg']='必传产品参数值不能为空';
                    alert_json_new(0,'缺少产品参数值：'.$value);
                }
            }
        }
      
      	if(empty($info['user_code']) || empty($info['user_key']) || empty($info['merchant_code'])){
			alert_json_new(0,'请传入正确的Appkey');
		}

		$map=array();
		$map['user_code']	=$info['user_code'];
		$map['user_key']	=$info['user_key'];
		$merchant_code		=$info['merchant_code'];

		$u=M('User');
		$u_info=$u->where($map)->find();
		$username=$u_info['username'];
		$db_name=C('DB_PREFIX_T').$username;
		C('db_config.DB_NAME',$db_name);

		$trans = M('',C('DB_PREFIX_T'), C('db_config'));
        $trans->startTrans();   // 开启事务
		$m=M('Pushorder',C('DB_PREFIX_T'), C('db_config'));
		$g=M('Pushordergoods',C('DB_PREFIX_T'), C('db_config'));
		$p=M('Printorder',C('DB_PREFIX_T'), C('db_config'));
		$pro=M('Product',C('DB_PREFIX_T'), C('db_config'));

		// $list=$param;
		$vs = $param;
		$push_data=array();
		
		$total_order_tax=0;//全部税金
		
		// foreach($list as $ks=>$vs){
			$data=array();
			$data_og=array();
			$print_order=array();
			
			$order_no = $vs['order_no'];
		
			//流水订单号-begin
			//流水单号兼容事务提交-begin
			// dump($serialNumber);
			$serialNumber_first=$this->serialNumber('Pushorder',$db_name);
			$len=strlen($serialNumber_first);
			$ser_nums=intval($serialNumber_first);
			$int_len=strlen($ser_nums);
			// $ser_nums=$ser_nums+$order_foreachcount;
			$str_nums="";
			for($j=0;$j<$len-$int_len;$j++){
				$str_nums.='0';
			}
			$serialNumber=$str_nums.$ser_nums;//流水单号兼容事务提交-end
			$serialNumber='P'.date("Ymd",time()).$serialNumber;//流水订单号
			if(isset($vs['warehouse_code']) && !empty($vs['warehouse_code'])){
				$data['warehouse_code']=$vs['warehouse_code'];//仓库编码
			}else{
				$data['warehouse_code']='11330213';//仓库编码
			}
		
			$data['order_no']=$serialNumber;//流水单号
			$data['old_order_no']=$order_no;//原单号
			//重复判断--beging
			$m_info=$m->where(array('old_order_no'=>$order_no))->find();
			if(!empty($m_info)){
				$trans->rollback();
				alert_json_new(0,$order_no."要导入的订单编号已经存在！");
				die;
			}else{
				$total_price=0;//订单总价格
			}
			//重复判断-end
			
			$data['buyer_name']		=trim($vs['buyer_name']);
			$data['buyer_phone']	=trim($vs['buyer_phone']);
			$data['buyer_idcard']	=trim($vs['buyer_idcard']);
			if(empty($data['buyer_idcard'])){
				$trans->rollback();
				alert_json_new(0,$order_no."订单对应的身份证号不能为空");
			}
			if(strlen($data['buyer_idcard'])!=18){
				$trans->rollback();
				alert_json_new(0,$data['old_order_no']."身份证号不等于18位");
			}

			$data['pay_number']	=$vs['pay_number'];
			// $data['come_from']	=$vs['platform_name'];//订单来源
			$data['platform_name']	=$vs['platform_name'];//订单来源
			
			if(isset($vs['cod']) && !empty($vs['cod'])){
				$data['cod']=1;
				if($vs['cod_money']=='0.00' || empty($vs['cod_money'])){
					$trans->rollback();
					alert_json_new(0,"cod订单的cod金额不能为0");
				}
				if(!empty($vs['cod_money'])){//cod导单金额
					$data['cod_money']	=$vs['cod_money'];
				}
			}

			$pay_company_cate=$vs['paycompany_code'];

			if(!empty($pay_company_cate)){
				$data['paycompany_code'] = $pay_company_cate;
			}else{
				$data['paycompany_code'] = '';
			}
			
			// if($pay_company_cate==1){	//支付宝
			// 	$data['paycompany_code'] = "ZF14021901";
			// }
			// if($pay_company_cate==2){	//微信
			// 	$data['paycompany_code'] = "440316T004";
			// }
			// if($pay_company_cate==3){	//新生支付
			// 	$data['paycompany_code'] = "671060987";
			// }

			//博奥百世推单-begin
			if(!empty($vs['apply_logistics'])){	//物流已申报
				$data['apply_logistics'] = 100;
			}
			if(!empty($vs['logiscompany_code'])){	//物流
				 //1：百世2:中通3：圆通4：顺丰5：申通
				$data['logiscompany_code'] = $vs['logiscompany_code'];
				$data['logistics_no'] = $vs['logistics_no'];
				if(empty($vs['apply_logistics'])){	//物流未申报
					$trans->rollback();
					alert_json_new(0,"物流未申报不能传运单号！");
				}
			}

			//博奥百世推单-begin
			$data['discount']=empty($vs['discount'])?0:$vs['discount'];//折扣
			$data['ems_fee']=empty($vs['order_freight'])?0:$vs['order_freight'];//快递费用
			$data['insure_amount']=empty($vs['insure_amount'])?0:$vs['insure_amount'];//保费
				
			$data['goods_tax']	=$vs['order_tax'];//订单税金
			$data['user_name']	=$vs['user_name'];
			
			if(strlen($vs['user_phone'])!=11){
				if(strlen($vs['buyer_phone'])==11){
					$data['user_phone']	=$vs['buyer_phone'];
				}else{
					alert(0,'手机号码错误');
				}
			}else{
				$data['user_phone']	=$vs['user_phone'];
			}

			// $data['user_idcard']	=$vs['user_idcard'];
			
			$data['province']	=$vs['user_province'];
			$data['city']	=$vs['user_city'];
			$data['area']	=$vs['user_area'];
			$data['user_address']	=$vs['user_address'];

			$data['platform_name']		=$vs['platform_name'];
			// $data['erp_mark_mailno']	=$vs['erp_mark_mailno'];
			$data['total_price']	=$vs['order_amount'];
			$transport	=$vs['trade_model'];//运输方式
			if(!empty($transport)){
				$data['transport_cate']=$transport;
			}
			$data['add_time']		= time();
		
			if(empty($data['total_price'])){
				$trans->rollback();
				alert_json_new(0,"总价不能为空！");
			}
			//添加订单
			if(empty($data['province']) || empty($data['city']) || empty($data['area'])){
				$trans->rollback();
				alert_json_new(0,'省市区不能为空');
			}

			$insert_id=$m->add($data);
			if(!$insert_id){
				$trans->rollback();
				alert_json_new(0,"写入订单信息失败，请检查传入参数！");
			}

			foreach($vs['order_detail'] as $k=>$v){
				foreach($v as $key=>$value){
					$v[$key]=trim($value);
				}
				
				$data_og=array();
				$data_og['bar_code']=$v['source_no'];
				$data_og['goods_nums']=$v['goods_nums'];
				// $data_og['goods_price']=$v['goods_price'];
				// if(empty($data_og['bar_code'])){
				// 	$trans->rollback();
				// 	alert_json_new(0,$order_no."的条码不能为空！");
				// }
				$data_og['goods_no']=$merchant_code.$v['goods_sn'];//商品编码+条形码
				
				$pros_map =array();
				$pros_map['goods_no'] = $data_og['goods_no'];
				$goods_info=$pro->where($pros_map)->find();
				
				if(empty($goods_info)){
					$trans->rollback();
					alert_json_new(0,"账册中没有查到对应商品信息【".$data_og['goods_no']."】");
				}else{
					if($goods_info['examined']==1){
						$trans->rollback();
						alert_json_new(0,"【".$data_og['goods_no']."】未审核通过");
					}
				}

				if(empty($data_og['bar_code'])){
					$data_og['bar_code'] = $goods_info['sn'];
				}
				if(empty($v['goods_price'])){
					$trans->rollback();
					alert_json_new(0,"没有接到导单价格！");
				}
				
				$data_og['goods_price']=$v['goods_price'];
				$data_og['goods_name']=$goods_info['name'];
				
				//读备案价格  --废弃-begin
				// if($merchant_code=='60070023OK' or $merchant_code=='91330109BA'){
					
					// if(empty($data_og['goods_price'])){			//有导入单价计入导入单价，没有导入单价读取备案单价
						// $data_og['goods_price']=$goods_info['price'];
					// }
				// }else{
					// $data_og['goods_price']=$goods_info['price'];//正常导单按备案金额扣税金
				// }
				//读备案价格  --废弃-end
				
				if(empty($data_og['goods_nums'])){
					$trans->rollback();
					alert_json_new(0,$order_no."商品数量不能为空");
				}
				//添加订单详情
				$data_og['order_id']=$insert_id;
				$res_gg=$g->add($data_og);
				if(!$res_gg){
					$trans->rollback();
					alert_json_new(0,"写入商品明细失败，请检查传人参数！");
				}
				$newgoods_info=array();
				$newgoods_info['goods_detail_id']=$res_gg;//商品详细id
				$newgoods_info['goods_nums']=$data_og['goods_nums'];//数量
				$newgoods_info['goods_no']=$data_og['goods_no'];//商品编码
				$push_data['detail'][]=$newgoods_info;
				
				$order_tax=0;//订单总税金
				$goods_price=sprintf("%.2f",$data_og['goods_price']*$data_og['goods_nums']);//商品总价格=单价*数量
				file_put_contents('./log/goods_price.log',date('Y-m-d H:i:s').var_export($goods_price,true).PHP_EOL,FILE_APPEND);//日志导出sql
				// $goods_tax=sprintf("%.2f",$goods_price*$goods_info['goods_tax']);//税金=商品总价格*税率
				$ems_fee=$data['ems_fee'];//运费
				$insure_amount=$data['insure_amount'];//保费
				$consumption_rate=$goods_info['consumption_rate'];//消费税率
				$increment_rate=$goods_info['increment_rate'];//增值税率
				$goods_tax=total_tax($goods_price,$ems_fee,$insure_amount,$consumption_rate,$increment_rate);//税金
				$total_price+=$goods_price;//总价格（不含税）
				if($total_price>=5000){
					$trans->rollback();
					alert_json_new(0,'总价格['.$total_price.']'.$data['old_order_no']."订单总金额不能大于5000");
				}
				$order_tax+=$goods_tax;//订单总税金
				$total_order_tax+=$goods_tax;//全部税金
			}

			$print_order['receiveMan']=$vs['user_name'];
			$print_order['receiveManPhone']=$vs['user_phone'];
			$print_order['receiveProvince']=$vs['user_province'];
			$print_order['receiveCity']=$vs['user_city'];
			$print_order['receiveCounty']=$vs['user_area'];
			$print_order['receiveManAddress']=$vs['user_address'];
			$print_order['txLogisticID']=$order_no;
			$print_order['order_no']=$serialNumber;
			$print_order['add_time']=time();//添加时间
			//添加面单
			$res_p=$p->add($print_order);
			if(!$res_p){
				$trans->rollback();
				alert_json_new(0,"写入面单信息失败，请检查传人参数！");
			}
		// }
		$api_url="http://www.t-cang.com/oms/index.php/Api/ErpApi/frozen_money";//保证金扣费预估接口
		$api_url_un="http://www.t-cang.com/oms/index.php/Api/ErpApi/unfreeze_money";//保证金扣费预估(释放金额)接口
		$api_push_data['customer']['user_code']=$u_info['user_code'];
		$api_push_data['customer']['user_key']=$u_info['user_key'];
		$api_push_data['data']['order_tax']=$total_order_tax;
		
		$push_data['warehouse_code']=$data['warehouse_code'];//一般仓仓库编码
		$url="http://www.t-cang.com/wmstest/index.php?s=/Pushreceiveapi/freez_storage";
		if(empty($push_data['warehouse_code'])){
			$trans->rollback();
			alert_json_new(0,'没有传入仓库编码');
		}
		if(empty($url)){
			$trans->rollback();
			alert_json_new(0,'请配置冻结库存接口');
		}
		
		$api_res=push($api_url,$api_push_data);

		$api_res=json_decode($api_res,true);

		file_put_contents('./log/order_tax.log',date('Y-m-d H:i:s').var_export($api_res,true).PHP_EOL,FILE_APPEND);//日志导出sql
		file_put_contents('./log/order_tax.log',date('Y-m-d H:i:s').var_export($api_push_data,true).PHP_EOL,FILE_APPEND);//日志导出sql
		
		if(!$api_res['flag']){
			$trans->rollback();
			alert_json_new(0,$api_res['tip']);
		}

		$res_edit=push($url,$push_data);
		$res_edit=json_decode($res_edit,true);

		$freez_storage_data = [
			'url'=>$url,
			'pusg_data'=>$push_data
		];
		file_put_contents('./log/freez_storage_data.log',date('Y-m-d H:i:s').var_export($freez_storage_data,true).PHP_EOL,FILE_APPEND);//日志导出sql

		file_put_contents('./log/freez_storage.log',date('Y-m-d H:i:s').var_export($res_edit,true).PHP_EOL,FILE_APPEND);//日志导出sql
		if(!$res_edit['status']){
			//释放冻结金额-begin
				$api_res_un=push($api_url_un,$api_push_data);
			//释放冻结金额-end
			$trans->rollback();
			alert_json_new(0,$res_edit['message']);
		}else{
			foreach($res_edit['detail'] as $kss=>$vss){
				$map_p['id']=$vss['goods_detail_id'];//订单明细对应商品id
				$data_p['goods_batch_no']=$vss['str'];//关联批次和数量
				// $data_p['goods_batch_no']=array('exp',"concat(goods_batch_no,',$str')");//关联批次和数量
				$g->where($map_p)->save($data_p);
			}
		}
		
		//将订单信息保存到定时任务   先推商城成功之后执行
		// if($map['user_code'] == 'PN1MBDNQ3G'){
		// 	$msg = [
		// 		'insert_id'=>$insert_id,
		// 		'order_no'=>$order_no,
		// 		'user_code'=>'PN1MBDNQ3G'
		// 	];
		// 	file_put_contents('./log/order_auto.log',date('Y-m-d H:i:s').var_export($msg,true).PHP_EOL,FILE_APPEND);//日志导出sql
		// 	if(!$this->pushoms_auto($map,$order_no)){
		// 		$trans->rollback();
		// 		alert_json_new(0,'推送失败');
		// 	}
		// }
		
		//扣库存-end
		$trans->commit();
		$return['flag']=1;
		$return['tip']="添加成功！";
		$this->ajaxReturn($return);
	}
	
	public function pushoms_auto($map,$order_no){
		$u=M('User');
		$p=M('PushorderCron');
		$pc=M('PushorderCronDetail');

		$u_info=$u->where($map)->find();
		$username=$u_info['username'];
		$db_name=C('DB_PREFIX_T').$username;
		C('db_config.DB_NAME',$db_name);
		$m=M('Pushorder',C('DB_PREFIX_T'),C('db_config'));

		// $m_list=$m->field('id')->where(array('status'=>1,'push_status'=>0))->select();

		 $m_list = $m->where(['old_order_no'=>$order_no])->find();

		if(empty($m_list)){
			$msg = ['code'=>0,'message'=>'没有要推送的新订单'];
			file_put_contents('./log/order_auto.log',date('Y-m-d H:i:s').var_export($msg,true).PHP_EOL,FILE_APPEND);//日志导出sql
			return false;
			// alert_json(0,'没有要推送的新订单');
			die;
		}
		$data_p['warehouse_code']='11330213';
		$data_p['username']=$username;
		$data_p['add_time']=time();

		$p_res=$p->add($data_p);
		if(!$p_res){
			$msg = ['code'=>0,'message'=>'添加计划任务失败'];
			file_put_contents('./log/order_auto.log',date('Y-m-d H:i:s').var_export($msg,true).PHP_EOL,FILE_APPEND);//日志导出sql
			return false;
		}else{
			$data=array();
			$ids=array();
			$time=time();
			// foreach($m_list as $k=>$v){
				$data['order_id']=$m_list['id'];
				$data['add_time']=$time;
				$data['porder_id']=$p_res;
				$ids[]=$m_list['id'];
			// }
			$res=$pc->add($data);
			if(!$res){
				$msg = ['code'=>0,'message'=>'失败'];
				file_put_contents('./log/order_auto.log',date('Y-m-d H:i:s').var_export($msg,true).PHP_EOL,FILE_APPEND);//日志导出sql
				return false;
			}else{
				$res_m=$m->where(array('id'=>array('in',$ids)))->save(array('push_status'=>2));
				return true;
				// alert_json(1,'推送成功'.count($m_list).'条');
			}
		}
	}
	//税金提示
	public function alert_tax(){
		$data=file_get_contents("php://input");
		file_put_contents('./log/alert_tax.log',date('Y-m-d H:i:s').$data.PHP_EOL,FILE_APPEND);//日志导出sql
		$u=M('User');
		$m=M('Member');
		$param=json_decode($data,true);
		if(!isset($data) || count($data)==0){
            $return['status']=0;
			$return['message']='没有数据';
			$this->ajaxReturn($return);
        }
		$map['user_code']=$param['user_code'];
		$member_id=$u->where($map)->getField('member_id');
		$data_m['oms_fee_status']=$param['tax_status'];
		$res=$m->where(array('id'=>$member_id))->save($data_m);
		if($res!==false){
			$return['status']=1;
			$return['message']='成功';
			$this->ajaxReturn($return);
		}else{
			$return['status']=1;
			$return['message']='失败';
			$this->ajaxReturn($return);
		}
	}
	//订单状态接口
	public function order_status(){
		$u=M('User');
		$data=file_get_contents("php://input");
		file_put_contents('./log/order_status'.date('Y-m-d').'.log',date('Y-m-d H:i:s').$data.PHP_EOL,FILE_APPEND);//日志导出sql
		// $data='[{"user_code":"AO20170621","order_no":"JY-2024659","apply_order_no":"C20170719138139","logistics_no":"50552940008922","is_pass":0,"is_deliver":0,"platform_name":"ERP","fail_reason":"feifeifeif"}]';
        $param=json_decode($data,true);
		if(!isset($data) || count($data)==0){
            $return['status']=0;
			$return['order_no']='';
			$this->ajaxReturn($return);
        }
		foreach($param as $k=>$v){
			$user_code=$v['user_code'];
			// $user_key=$v['user_key'];
			$map['old_order_no']=$v['order_no'];
			$map['status']=1;
			$data_pushorder=array();
			$data_pushorder['apply_order_no']=$v['apply_order_no'];
			$data_pushorder['logistics_no']=$v['logistics_no'];
			$data_pushorder['is_pass']=$v['is_pass'];
			$data_pushorder['is_delivery']=$v['is_deliver'];
			$data_pushorder['fail_reason']=$v['fail_reason'];
			$data_pushorder['actual_weight']=$v['actual_weight'];//实际重量
			if(empty($v['deliver_time'])){
				$data_pushorder['delivery_time']=0;//出库时间
			}else{
				$data_pushorder['delivery_time']=$v['deliver_time'];//出库时间
			}
			
			$u_info=$u->field('username')->where(array('user_code'=>$user_code))->find();
			$db_name=C('DB_PREFIX_T').$u_info['username'];
			C('db_config.DB_NAME',$db_name);
			$m=M('Pushorder', C('DB_PREFIX_T'), C('db_config'));
			$res=$m->where($map)->save($data_pushorder);
			// echo $m->getlastsql();
			// die;
			$return[$k]['order_no']=$v['order_no'];
			if($res===false){
				$return[$k]['status']=0;
			}else{
				//推送分销商-begin
				$m_info=$m->field('order_erp,agent_id')->where($map)->find();
				// echo $m->getlastsql();
				// die;
				$agent_id=$m_info['agent_id'];
				if(!empty($agent_id)){
					// $agent_url="http://erpvr.jm.com/index.php/Agent/Api/order_status";//分销订单状态接口
					$agent_url="http://www.t-cang.com/erpts/index.php/Agent/Api/order_status";
					$data_pushorder['order_no']=substr($v['order_no'],-14);//原订单号
					$data_pushorder['agent_id']=$agent_id;
					$res_agent = push($agent_url,$data_pushorder);
					$res_agent=json_decode($res_agent,true);
					if(!$res_agent['status']){
						file_put_contents('./log/order_status_agent.log',date('Y-m-d H:i:s').var_export($res_agent,true).PHP_EOL,FILE_APPEND);//日志导出sql
					}
				}
				//推送分销商-end
				//推送订单收集系统-begin
				$order_erp=$m_info['order_erp'];
				if(!empty($order_erp)){
					$agent_url="http://192.168.0.8:8080/com.botao.erp.api/orderDetails/receiveData.do";//抓单订单状态接口
					// $agent_url="http://www.t-cang.com/erpts/index.php/Agent/Api/order_status";
					$data_pushorder_ss=array();
					$data_pushorder_ss['logisticsId']=$v['logiscompany_code'];//物流企业编号
					$data_pushorder_ss['logisticsName']=$v['logiscompany_name'];//物流单号
					$data_pushorder_ss['waybill']=$v['logistics_no'];//物流单号
					if(empty($v['deliver_time'])){
						$data_pushorder_ss['deliveryTime']=0;//出库时间
					}else{
						$data_pushorder_ss['deliveryTime']=$v['deliver_time'];//出库时间
					}
					$data_pushorder_ss['orderId']=$v['order_no'];//原订单号
					$res_agent = pushjava($agent_url,$data_pushorder_ss);
					dump($res_agent);
					die;
					$res_agent=json_decode($res_agent,true);
					if(!$res_agent['status']){
						file_put_contents('./log/order_status_agent.log',date('Y-m-d H:i:s').var_export($res_agent,true).PHP_EOL,FILE_APPEND);//日志导出sql
					}
				}
				//推送订单收集系统-end
				$return[$k]['status']=1;
			}
		}
		$this->ajaxReturn($return);
	}
	
	//流水号
	public function serialNumber($tablename,$db_name){
		C('db_config.DB_NAME',$db_name);
		$m=M($tablename, C('DB_PREFIX_T'), C('db_config'));
		//当日流水号生成
		$map['_string']="add_time-UNIX_TIMESTAMP(DATE(NOW()))>0 and add_time-UNIX_TIMESTAMP(DATE(NOW()))<86400";
		$count=$m->where($map)->count();//当天添加的采购单数
		
		$count=$count+1;
		$serial_number="";
		if($count<10){
			$serial_number='0000'.strval($count);
		}
		if($count>=10 and $count<100){
			$serial_number='000'.$count;
		}
		if($count>=100 and $count<1000){
			$serial_number='00'.$count;
		}
		if($count>=1000 and $count<10000){
			$serial_number='0'.$count;
		}
		return $serial_number;//流水序号
	}

	//订单查询
	public function orderSearch(){
		$data=file_get_contents("php://input");
		file_put_contents('./log/order_search'.date('Y-m-d').'.log',date('Y-m-d H:i:s').$data.PHP_EOL,FILE_APPEND);//日志导出sql
		
		$data=json_decode($data,true);
		if(empty($data)){
			alert_json_new(0,'请求数据不能为空','');
		}
		// $data=[
		// 	'method'=>'orderSearch',    //Y（请求方法）
		// 	// 'accesstoken'=>'', //Y（Accesstoken和Appkey有什么区别？？？？？）
		// 	'appkey'=>'test111', //Y（Appkey）
		// 	'sign'=>'1111', //Y（加签）
		// 	'timestamp'=>time(),     //Y（时间）      
		// 	'format'=>'json', //Y（返回类型  现在只返回json）
		// 	'Versions'=>'1', //N（版本号）

		// 	'param'=>[
		// 		// 'searchtype'=>'',//0：未归档订单，1查询已归档订单  Y
		// 		'begintime'=>'2019-1-02', //开始时间  Y
		// 		'endtime'=>'2019-1-10',	//结束时间  Y
		// 		'pageno'=>'3',	//页码  Y
		// 		'pagesize'=>'1',	//每页条数  Y
		// 		'timetype'=>'2',	//查询时间类型  N  (1出库时间和2导入时间  默认查询导入时间)
		// 		'searchstatus'=>'',//订单状态  N   （1待申报  2已申报  3打包中  4已出库  默认全部）
		// 		'operationtype'=>'',//订单类型  N   （4行邮  2保税  1一般  3直邮  默认全部）
		// 		'searchno'=>'',//订单编号  N         （原始订单号）
		// 		// 'relationno'=>'',//关联单号（原始单号）  N   （？？？？）
		// 		'warehouseno'=>'',//仓库编码  N      （仓库编码）
		// 		// 'querymarkup'=>'',//单据查询标记(1 已经查询 2 被取消查询标记)  N    （？？？？）
		// 		// 'reservedword'=>'',//等于1时候，查询出来的 货品会自动关联上拆分前的 原始单单号，解析不到的赋值为空  N  （？？？？）
		// 		// 'searchname'=>'',//店铺名  N   （ERP系统有店铺名吗？？？？）
		// 	]
		// ];

		switch ($data['appkey']) {
        	case 'test111':
        		$app_secret = '123456';
        		// alert_json_new(0,'测试接口关闭');
        		// $info['user_code']='';
				// $info['user_key']='';
				// $info['merchant_code']='';
				$info['user_code']='PN1MBDNQ3G';
				$info['user_key']='PN1MBDNQ3G';
				$info['merchant_code']='PN1MBDNQ3G';
        		break;
        	case 'PNZgKvQpKfnWitLg':
        		$app_secret = 'Q5BYL4osudAXrbvrfGMmR76I3SKQXSg7';
        		$info['user_code']='PN1MBDNQ3G';
				$info['user_key']='PN1MBDNQ3G';
				$info['merchant_code']='PN1MBDNQ3G';
        		break;
        	default:
        		$app_secret = '';
        		break;
        }

        if(!$app_secret){
        	alert_json_new(0,'密钥参数错误','');
        }

        if($data['timestamp']*1<time()*1-60){
        	alert_json_new(0,'请求过期,请重新发起','');
        }

        $new_str = genVerify($param);
        $sign = md5($app_secret.'appkey'.$app_key.'param'.$new_str.'timestamp'.$timestamp.$app_secret);
		// $data['Sign'] = $sign;
        if($data['sign'] != $sign){
        	$msg=[
        		'get_sign' =>$data['sign'],
        		'sign'=>$sign,
        		'data'=>$new_str
        	];
			alert_json_new(0,'验签失败',$msg);
        }

      	if(empty($info['user_code']) || empty($info['user_key']) || empty($info['merchant_code'])){
			alert_json_new(0,'请传入正确的Appkey','');
		}

		//验证应用级参数
		if(is_array($data['param'])){
            $data = $data['param'];
        }else{
            $data = json_decode($data['param'],true);
        }

		//必传参数-订单表
        $must_param_order = ['begintime','endtime','pageno','pagesize'];
        foreach ($must_param_order as $value){
            if(!isset($data[$value]) || empty($data[$value])){
                alert_json_new(0,'缺少参数或参数值：'.$value);
            }
        }
		
        //时间处理
		$start_time = strtotime($data['begintime']);
		$now = time();
		if($start_time > $now){
			alert_json_new(0,'查询时间错误','');
		}
		$where['start_time'] = $start_time;

		if(empty($data['endtime'])){
			$where['end_time'] = $now;
		}else{
			$where['end_time'] = strtotime($data['endtime']);
		}
		$where['pageno'] = $data['pageno'];
		$where['pagesize'] = $data['pagesize'];
		$where['timetype'] = isset($data['timetype'])?$data['timetype']:2;  //1出库时间 2导入时间

		if($data['searchstatus']){ //订单状态  1待推送 2申报中 3打包中 4已出库
			$where['order_status'] = $data['searchstatus'];
		}

		if($data['searchno']){//订单号（原始）
			$where['order_no'] = $data['searchno'];
		}

		if($data['warehouseno']){ //仓库编码
			$where['warehouse_code'] = $data['warehouseno'];
		}

		$map=array();
		$map['user_code']	=$info['user_code'];
		$map['user_key']	=$info['user_key'];
		$merchant_code		=$info['merchant_code'];

		$order_info = $this->getOrderInfo($where,$map);

		alert_json_new(1,'SUCCESS',$order_info);
	}

	protected function getOrderInfo($getwhere,$map){
		$u=M('User');
		$u_info=$u->where($map)->find();
		$username=$u_info['username'];
		$db_name=C('DB_PREFIX_T').$username;
		C('db_config.DB_NAME',$db_name);

		$trans = M('',C('DB_PREFIX_T'), C('db_config'));
        // $trans->startTrans();   // 开启事务
		$pushorder=M('Pushorder',C('DB_PREFIX_T'), C('db_config'));
		$pushordergoods=M('Pushordergoods',C('DB_PREFIX_T'), C('db_config'));
		$printorder=M('Printorder',C('DB_PREFIX_T'), C('db_config'));
		$product=M('Product',C('DB_PREFIX_T'), C('db_config'));

		$page = $getwhere['pageno'];
		$pagesize = $getwhere['pagesize'];
		$page_f = $page*$pagesize; //偏移量

		if($getwhere['timetype']==1){//出库时间
			$where['delivery_time'] = ['between',[$getwhere['start_time'],$getwhere['end_time']]];
		}else{//创建时间（导入时间）
			$where['add_time'] = ['between',[$getwhere['start_time'],$getwhere['end_time']]];
		}

		if(isset($getwhere['order_no']) && !empty($getwhere['order_no'])) {
			$where['order_no'] = $getwhere['order_no'];
		}

		if(isset($getwhere['warehouse_code']) && !empty($getwhere['warehouse_code'])) {
			$where['warehouse_code'] = $getwhere['warehouse_code'];
		}

		if(isset($getwhere['order_status']) && !empty($getwhere['order_status'])) {
			switch ($getwhere['order_status']) {
				case 1://未推送
					$where['is_pass']=array('EXP','IS NULL');
					// $where['is_pass'] = 0;
					$where['is_delivery'] = 0;
					$where['push_status'] = '-1';
					break;
				case 2://已推送
					$where['is_pass']=array('EXP','IS NULL');
					$where['is_delivery'] = 0;
					$where['push_status'] = 1;
					break;
				case 3://正在推送
					$where['is_pass']=array('EXP','IS NULL');
					$where['is_delivery'] = 0;
					$where['push_status'] = 2;
					break;
				case 4://申报中
					$where['is_pass']=array('EXP','IS NULL');
					$where['is_delivery'] = 0;
					$where['push_status'] = 1;
					break;
				case 5://未放行
					$where['is_pass'] = 0;
					$where['is_delivery'] = 0;
					$where['push_status'] = 1;
					break;
				case 6://打包中
					$where['is_pass'] = 2;
					$where['is_delivery'] = 0;
					$where['push_status'] = 1;
					break;
				case 7://已出库
					$where['is_pass'] = 1;
					$where['is_delivery'] = 1;
					$where['push_status'] = 1;
					break;
				// case 8://已出库
				// 	$where['is_pass'] = 1;
				// 	$where['is_delivery'] = 1;
				// 	$where['push_status'] = 1;
				// 	break;
			}
		}
		$order_info = $pushorder->where($where)->limit($page_f,$pagesize)->select();

		$order = [];
		foreach ($order_info as $key => $value) {
			$order[$key]['tradeid']=$value['id']; //单号ID
			$order[$key]['regtime']=$value['add_time'];//登记时间(添加时间) 

			switch ($value['push_status']) {
				case '-1':
					$order[$key]['tradestatus'] = '未推送';
					break;
				case '2':
					$order[$key]['tradestatus'] = '正在推送';
					break;
				case '1':
					switch ($value['is_deliver']) {
						case '0':
							switch ($value['is_pass']) {
								case '0':
									$order[$key]['tradestatus'] = '未放行';
									break;
								case '1':
									$order[$key]['tradestatus'] = '已经出库';
									break;
								case '2':
									$order[$key]['tradestatus'] = '打包中';
									break;
								default:
									$order[$key]['tradestatus'] = '申报中';
									break;
							}
							break;
						case '1':
							$order[$key]['tradestatus'] = '已出库';
							break;
					}
					break;
		
			}
			// //订单状态
			// if($value['push_status'] == '-1'){
			// 	if($value['is_pass']){//是否放行
			// 		if($value['is_delivery']){//是否出库
			// 			$order[$key]['tradestatus']='已出库';
			// 		}else{
			// 			$order[$key]['tradestatus']='打包中';
			// 		}
			// 	}else{
			// 		$order[$key]['tradestatus']='申报中';
			// 	}
			// }else{
			// 	$order[$key]['tradestatus'] = '未推送';
			// }

			$order[$key]['tradeno']=$value['order_no'];//订单号(ERP自己生成的)		
			$order[$key]['tradeno2']=$value['old_order_no'];//原始单号
			$order[$key]['warehouseno']=$value['warehouse_code'];//仓库编号

			switch ($value['warehouse_code']) {
				case '11330213':
					$order[$key]['warehousename']='天众下沙仓';//仓库名
					break;
				default:
					$order[$key]['warehousename']='';//仓库名
					break;
			}
			
			$order[$key]['logisticlistno']=$value['logistics_no'];//物流编号
			$order[$key]['logisticname']=$value['logiscompany_name'];//物流名
			$order[$key]['couponvalue']='';//抵扣金额 
			$order[$key]['favourabletotal']='';//优惠金额(折扣)
			$order[$key]['total_amount']=$value['total_price'];
			$order[$key]['remark']=$value['mark1'];//备注
			$order[$key]['sndtime']=$value['delivery_time'];//发货时间 (出库时间)
			$order[$key]['postagetotal']=$value['ems_fee'];//应收邮资 (推过来运费)
			$order[$key]['province']=$value['province'];//省
			$order[$key]['city']=$value['city'];//市
			$order[$key]['town']=$value['area'];//区
			$order[$key]['chargeid']=$value['pay_number'];// 支付单号
			$order[$key]['packagedweight']=$value['pack_weight'];//包裹重量
			$order[$key]['providername']=$value['company_name'];//供应商姓名
			$order[$key]['providerno']=$value['company_code'];//供应商编号
			$order[$key]['tradefrom']=$value['come_from'];//订单来源	
			$order[$key]['invoicepayerphone']=$value['user_phone'];//消费者电话
			$order[$key]['invoicepayeraddr']=$value['user_address'];//消费者地址
			$goods_info = $this->getProductsInfo($pushordergoods,$value['id']);
			$order[$key]['goodslist'] = $goods_info;  //产品信息
		}
		return $order;
	}

	protected function getProductsInfo($pushordergoods,$order_id){
		$goods_info = $pushordergoods->where(['order_id'=>$order_id])->select();
		$goods = [];
		foreach($goods_info as $k=>$value){
			$goods[$k]['recid']=$value['id']; //记录id
			$goods[$k]['goodsno']=$value['goods_no']; //货品编号
			$goods[$k]['goodsname']=$value['goods_name']; //品名
			$goods[$k]['goodscount']=$value['goods_nums']; //数量
			$goods[$k]['price']=$value['goods_price']; //单价
			$goods[$k]['goodsmoney']=$value['goods_nums']*$value['goods_price']; //金额
			$goods[$k]['remark']=$value['bz']; //备注
			$goods[$k]['barcode']=$value['bar_code']; //条码
		}
		return $goods;
	}
}